<template>
  <div>
    <zm-form
      :model="form"
      :rules="$product.rules"
      ref="form"
      label-width="150px"
      label-position="right"
    >
      <zm-form-item label="产品名称" prop="name">
        <zm-input
          class="w300"
          v-model="form.name"
          maxlength="30"
          show-word-limit
          placeholder="请输入产品名称，建议不超过30个字"
          @change="handleProductNameChange"
        />
      </zm-form-item>
      <zm-form-item label="产品类目">
        <el-cascader
          class="w300"
          v-model="childCategory"
          :options="categoryList"
          :show-all-levels="false"
          :props="{ value: 'id', label: 'name' }"
          clearable
        ></el-cascader>
      </zm-form-item>
      <zm-form-item label="产品类型" prop="type">
        <el-radio-group v-model="form.type" @change="handleChangeType">
          <el-radio label="1">兑换券</el-radio>
          <el-radio label="2">卖品券</el-radio>
          <el-radio label="5">优惠券</el-radio>
          <el-radio label="3">点卡</el-radio>
          <el-radio label="4">次卡</el-radio>
        </el-radio-group>
      </zm-form-item>
      <zm-form-item label="卡名称" v-if="form.type === '3'" prop="cardName">
        <zm-input
          class="w300"
          v-model="form.cardName"
          maxlength="30"
          show-word-limit
          clearable
          placeholder="请输入卡名称，建议不超过30个字"
        />
      </zm-form-item>
      <zm-form-item label="业务类型" prop="businessType" v-if="+form.type !== 4">
        <zm-data-select
          v-model="form.businessType"
          :list="businessTypeList"
          label-name="name"
          value-key="value"
          class="w300"
          clearable
          placeholder="请选择对应业务类型"
        >
        </zm-data-select>
      </zm-form-item>
      <zm-form-item label="销售单类型" prop="salesType">
        <el-radio-group v-model="salesType" @change="salesTypeChange">
          <el-radio label="-1">全部类型</el-radio>
          <el-radio label="2">指定类型</el-radio>
        </el-radio-group>
        <zm-data-select
          v-model="form.salesType"
          :list="saleOrderTypeList"
          placeholder="销售单类型"
          multiple
          str
          class="w200"
          v-if="salesType === '2'"
        ></zm-data-select>
      </zm-form-item>
      <!-- 兑换券、卖品券展示 strat -->
      <template v-if="isShowCoupon">
        <zm-form-item label="券名称">
          <zm-input
            class="w300"
            v-model="form.couponName"
            maxlength="30"
            show-word-limit
            clearable
            placeholder="请输入券名称，建议不超过30个字"
          />
        </zm-form-item>
        <!-- 优惠券不展示产品面值 -->
        <zm-form-item label="产品面值" prop="parValue" v-if="+form.type !== 5">
          <zm-input
            class="w300"
            v-model="form.parValue"
            type="number"
            clearable
            placeholder="将实际在券面上展示"
          >
            <template slot="append">
              元
            </template>
          </zm-input>
        </zm-form-item>
        <!-- 优惠券展示优惠面值 -->
        <zm-form-item label="优惠面值" prop="isDiscount" v-if="+form.type === 5">
          <zm-radio-group v-model="form.isDiscount">
            <el-radio label="0">不限额优惠</el-radio>
            <el-radio label="1">限额优惠</el-radio>
          </zm-radio-group>
          <zm-form-item prop="couponPrice" v-if="+form.isDiscount === 0" class="mt10">
            <span>优惠面值</span>
            <zm-input class="w200" v-model="form.couponPrice" type="number" clearable>
              <template slot="append">
                元
              </template>
            </zm-input>
          </zm-form-item>
          <div v-if="+form.isDiscount === 1" class="mt10">
            <zm-form-item prop="fullPrice" class="dib">
              <span>满</span>
              <zm-input class="w150" v-model="form.fullPrice" type="number" clearable>
                <template slot="append">
                  元
                </template>
              </zm-input>
              <span>可以优惠</span>
            </zm-form-item>

            <zm-form-item prop="reductionPrice" class="dib">
              <zm-input class="w150" v-model="form.reductionPrice" type="number" clearable>
                <template slot="append">
                  元
                </template>
              </zm-input>
            </zm-form-item>
          </div>
        </zm-form-item>
        <zm-form-item label="券兑换范围" prop="exchangeRange">
          <zm-checkbox-group v-model="form.exchangeRange" @change="handlePushRuleItem">
            <el-checkbox label="1">线上</el-checkbox>
            <el-checkbox label="2" v-if="+form.type !== 5"> 线下 </el-checkbox>
            <el-checkbox label="3" v-if="+form.type === 1 && exchangeRangeVal.includes('1')">
              心选膨胀
            </el-checkbox>
          </zm-checkbox-group>
        </zm-form-item>
      </template>
      <!-- 兑换券、卖品券展示 end -->

      <!-- 产品配置新增产品使用范围【除了次卡,卖品劵不新增次字段】 -->
      <zm-form-item label="产品使用范围" v-if="+form.type !== 4 && +form.type !== 2">
        <zm-checkbox-group v-model="form.useScope" @change="handlePushRuleItem">
          <el-checkbox label="1">电影</el-checkbox>
          <el-checkbox label="2">心选</el-checkbox>
        </zm-checkbox-group>
      </zm-form-item>

      <zm-form-item :label="+form.type === 1 ? '券可用渠道' : '可用渠道'" v-if="+form.type !== 4">
        <zm-radio-group v-model="form.isLimitChannel" @change="setChannelID">
          <el-radio label="0">不限制</el-radio>
          <el-radio label="1">指定渠道</el-radio>
        </zm-radio-group>
        <zm-form-item class="mt10" v-if="+form.isLimitChannel === 1" prop="channelId">
          <zm-data-select
            v-model="form.channelId"
            :list="channelList"
            class="w300"
            clearable
            placeholder="请选择指定渠道，可多选"
            multiple
            str
          >
          </zm-data-select>
        </zm-form-item>
      </zm-form-item>

      <!-- 点卡展示 start -->
      <div v-if="+form.type === 3">
        <zm-form-item label="是否开放充值" prop="isOpenRecharge">
          <zm-radio-group v-model="form.isOpenRecharge">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </zm-radio-group>
        </zm-form-item>
        <zm-form-item label="销售比例" prop="saleScalePrice" class="dib">
          <zm-input
            class="w100"
            placeholder="金额"
            v-model="form.saleScalePrice"
            type="number"
            clearable
          ></zm-input>
          :
        </zm-form-item>
        <zm-form-item prop="saleScalePoint" label-width="0px" class="dib">
          <zm-input
            class="w100"
            placeholder="点数"
            v-model="form.saleScalePoint"
            type="number"
            clearable
          ></zm-input>
          <span>销售的时候卡面金额与卡内点数的比例</span>
        </zm-form-item>
        <zm-form-item label="消费比例" prop="consumptionScalePrice">
          <zm-input
            class="w100"
            placeholder="金额"
            v-model="form.consumptionScalePrice"
            type="number"
            clearable
          ></zm-input>
          <span>元扣除</span>
          <zm-form-item prop="consumptionScalePoint" label-width="0px" class="dib">
            <zm-input
              class="w100"
              placeholder="点数"
              v-model="form.consumptionScalePoint"
              type="number"
              clearable
            ></zm-input>
            <span>点，比例越大扣除点数越多</span>
          </zm-form-item>
        </zm-form-item>
      </div>
      <!-- 点卡展示 end -->
      <zm-form-item label="解绑配置" v-if="+form.type !== 4">
        <zm-radio-group v-model="form.isUnbundling">
          <el-radio label="0">不可解绑</el-radio>
          <el-radio label="1">可解绑</el-radio>
        </zm-radio-group>
      </zm-form-item>
      <zm-form-item label="转赠配置" v-if="form.type !== '4'">
        <!-- v-if="isShowIsGive" -->
        <!-- CRM v1.1.0 需求是所有产品类型都可以设定 转赠配置 -->
        <zm-radio-group v-model="form.isGive">
          <div class="df-center">
            <el-radio label="0">不可转赠</el-radio>
            <el-radio label="1">可转赠</el-radio>
            <tip
              v-if="form.type !== '4'"
              content="若配置为可转赠，转赠不限制次数，可无限次进行转赠，若卡券已经被使用则无法进行转赠操作"
            ></tip>
          </div>
        </zm-radio-group>
      </zm-form-item>

      <zm-form-item label="产品可售部门" prop="isLimitExpiredTime">
        <zm-radio-group v-model="form.isApartment">
          <el-radio label="1">全部部门</el-radio>
          <el-radio label="2">指定部门</el-radio>
        </zm-radio-group>
      </zm-form-item>
      <zm-form-item label="配置卡面" v-if="form.type == 3">
        <zm-button type="primary" @click="onCardSurface">配置</zm-button>
        <p class="tip-card">若未配置,则使用默认卡面</p>
        <!--         <zm-image-upload
          class="image-preview"
          v-if="form.cardSurfaceId && imageUrl"
          style="width:450px !important"
          v-model="imageUrl"
          @on-remove="hangeDelImage"
          :limit="1"
        ></zm-image-upload> -->
        <div class="image-pre" v-show="form.cardSurfaceId && showcardSurfaceImage()">
          <el-image
            ref="imagePreview"
            :src="showcardSurfaceImage()"
            style="width: 380px; height: 200px; border-radius: 16px;"
            fit="cover"
            :preview-src-list="[showcardSurfaceImage()]"
          >
          </el-image>
          <div class="delete-img">
            <div class="fixed-img">
              <i style="margin-right: 20px;" class="el-icon-search" @click="handlePreview"></i>
              <i class="el-icon-delete" @click="handleDelImage"></i>
            </div>
          </div>
        </div>
      </zm-form-item>
      <zm-form-item label="所属公司" v-if="+form.isApartment === 2" prop="companyId">
        <zm-data-select
          v-model="form.companyId"
          @change="companyChange"
          api="getCompanyList"
          label-name="companyName"
          value-key="companyId"
          placeholder="请选择公司"
          class="w320 "
        ></zm-data-select>
      </zm-form-item>
      <zm-form-item
        label="所属部门"
        v-if="+form.isApartment === 2 && form.companyId && apartmentList.length"
        prop="apartmentId"
      >
        <tree-select
          v-model="form.apartmentId"
          :tree="apartmentList"
          :tree-props="{ label: 'name', valueKey: 'value' }"
          :is-checkbox="true"
          placeholder="请选择部门"
          class="w300"
        ></tree-select>
      </zm-form-item>

      <!-- 次卡展示 start -->
      <div v-if="+form.type === 4">
        <zm-form-item label="关联兑换券产品" prop="couponProductId">
          <zm-button icon="el-icon-plus" size="mini" class="mb10" @click="onSelectProduct">
            添加产品
          </zm-button>

          <span class="fc-blue"> 已添加产品记录{{ couponProductIdLen }} 条</span>
        </zm-form-item>
        <zm-form-item label="产品有效时间" prop="isLimitExpiredTime">
          <zm-radio-group v-model="form.isLimitExpiredTime">
            <el-radio label="0">不限制</el-radio>
            <el-radio label="1" :disabled="+form.type === 4">限制</el-radio>
          </zm-radio-group>
          <zm-date-picker
            class="mt10"
            v-if="+form.isLimitExpiredTime === 1"
            type="datetimerange"
            :target="form"
            start-key="expiredStartTime"
            end-key="expiredEndTime"
          />
        </zm-form-item>
      </div>
      <!-- 次卡展示 end -->

      <zm-form-item label="使用规则" v-if="+form.type !== 4">
        <zm-input
          class="w300"
          v-model="form.usageRules"
          :autosize="{ minRows: 10 }"
          maxlength="1000"
          type="textarea"
          show-word-limit
          placeholder="请输入使用规则"
          clearable
        />
      </zm-form-item>
      <zm-form-item label="产品备注" v-if="+form.type !== 4">
        <zm-input
          class="w300"
          v-model="form.remark"
          :autosize="{ minRows: 6 }"
          maxlength="200"
          type="textarea"
          show-word-limit
          placeholder="请输入产品备注"
          clearable
        />
      </zm-form-item>
      <!-- 次卡添加产品 -->
      <select-product
        v-if="SelectProductParams.visible"
        v-model="SelectProductParams.visible"
        @handle-after="selectProductCallBack"
        :is-time-car="true"
        :checked-arr="checkedArr"
        :is-approve="isApprove"
      ></select-product>
      <select-surface
        v-if="showCardSurface"
        v-model="showCardSurface"
        :card-surface-id="form.cardSurfaceId"
        @handle-after="selectSurfaceCallBack"
      ></select-surface>
    </zm-form>
  </div>
</template>

<script>
import tableMixin from '@/mixins/zmTableMixin'
import SelectProduct from '@/components/SelectProduct'
import SelectSurface from '@/components/SelectSurface'
import Tip from '@/components/Tip'
import publicApis from '@/api/src/public'
import cloudApis from '@/api/src/cloud'
import TreeSelect from '@/components/TreeSelect'
import productApis from '@/api/src/product'
import cardSurface from '@/api/src/cardSurface'
import { getBusinessType } from '@/api/src/productDraft.js'
import ZmImageUpload from '@/components/ZmUpload/components/ImageUpload.vue'
export default {
  name: 'StepOne',
  components: { SelectProduct, TreeSelect, Tip, SelectSurface, ZmImageUpload },
  inject: ['$product'],
  mixins: [tableMixin],
  data() {
    return {
      businessTypeList: [], // 业务类型下拉数据
      categoryList: [], // 产品类目下拉
      SelectProductParams: {
        visible: false
      },
      disabledValue: [], // 可售部门禁用
      apartmentList: [], // 可售部门下拉项
      channelList: [], // 渠道下拉项
      isShowSelectApartment: false,
      apartmentValueList: [],
      salesType: '-1',
      cardSurfaceList: [],
      showCardSurface: false,
      imageUrl: ''
    }
  },
  computed: {
    form: {
      get() {
        return this.$product.form
      },
      set(val) {
        this.$nextTick(() => {
          this.$product.form = val
        })
      }
    },
    childCategory: {
      get() {
        return this.form.childCategory ? this.form.childCategory : ''
      },
      set(v) {
        this.$set(this.form, 'childCategory', v[1])
      }
    },
    // 兑换券、卖品券展示
    isShowCoupon() {
      const _arr = ['1', '2', '5']
      return _arr.includes(this.form.type)
    },
    // 关联兑换券产品ID长度
    couponProductIdLen() {
      if (this.form.couponProductId) {
        const arr = this.form.couponProductId.toString().split(',')
        return arr.length
      } else {
        return 0
      }
    },
    // 添加产品回填ID集合
    checkedArr() {
      if (this.form.couponProductId) {
        return this.form.couponProductId.toString().split(',')
      } else {
        return []
      }
    },
    // 是否展示转赠配置
    isShowIsGive() {
      if (this.form.type === '4') {
        return false
      } else {
        return true
      }
    },
    // 是否为审批流进来的编辑页面
    isApprove() {
      return this.$product.isApprove
    },
    // 将form.exchangeRange值转为数组
    exchangeRangeVal() {
      return this.form.exchangeRange.split(',')
    },
    saleOrderTypeList() {
      return this.$auth.getBaseDataByType('saleOrderType').filter((item) => {
        return ['1', '2', '3', '4', '5'].includes(item.value)
      })
    }
  },
  watch: {},
  created() {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    async init() {
      // this.apartmentList = await publicApis.apartmentList()
      this.channelList = await cloudApis.getChannelList()
      this.categoryList = await publicApis.getProductCategoryList()
      this.cardSurfaceList = await cardSurface.getList()
      this.getBusinessTypeList()
      // let idsList = []
      // this.apartmentList.forEach((item) => {
      //   idsList.push(item.value)
      //   if (item.children) {
      //     item.children.forEach((i) => {
      //       idsList.push(i.value)
      //     })
      //   }
      // })
      // this.apartmentValueList = idsList
      this.companyChange()
      // 处理次卡类型数据
      if (this.form.type === '4' && this.form.couponProductId) {
        const params = {
          checkStatus: '3',
          productType: '1,2,5',
          ids: this.form.couponProductId,
          dataType: this.isApprove ? '-2' : ''
        }
        const res = await productApis.getPageList(this.assignQuery(params))
        const idsArr = res.list.map((i) => i.id)
        this.selectProductCallBack(idsArr)
      }
      this.salesType = ['', '-1'].includes(this.form.salesType) ? '-1' : '2'
    },

    async getBusinessTypeList() {
      const _res = await getBusinessType({ type: this.isShowCoupon ? 'coupon' : 'card' })
      this.businessTypeList = _res.data
    },
    // 处理可售部门编辑回填
    // handleInitApartment () {
    //   // console.log('apartmentId', this.form.apartmentId)
    //   if (this.form.apartmentId) {
    //     const _arr = this.form.apartmentId.split(',')
    //     // console.log('current:', _arr.length, 'all:', this.apartmentValueList.length)
    //     if (_arr.length === this.apartmentValueList.length) {
    //       this.isApartment = '1'
    //     } else {
    //       this.isApartment = '2'
    //     }
    //   }
    // },
    // 次卡添加产品
    onSelectProduct() {
      this.SelectProductParams = {
        visible: true
      }
    },
    // 配置卡面
    onCardSurface() {
      this.showCardSurface = true
    },
    showcardSurfaceImage() {
      if (this.form.cardSurfaceId) {
        const _res = this.cardSurfaceList.find((item) => {
          return item.id === this.form.cardSurfaceId
        })
        return _res ? _res.image : ''
      } else {
        return ''
      }
    },
    handleDelImage() {
      this.form.cardSurfaceId = ''
    },
    selectProductCallBack(val) {
      this.$set(this.form, 'couponProductId', val.join(','))
      // 控制stepThree的请求数据动作
      this.$emit('handle-after')
    },
    selectSurfaceCallBack(val) {
      this.$set(this.form, 'cardSurfaceId', val.id)
      const _res = this.cardSurfaceList.find((item) => {
        return item.id === this.form.cardSurfaceId
      })
      this.imageUrl = _res ? _res.image : ''
    },
    salesTypeChange(val) {
      this.form.salesType = val === '-1' ? '-1' : ''
    },
    // 表单校验
    async handleFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject(`基本信息`)
          }
        })
        if (this.form.apartmentId) {
          resolve()
        } else {
          _valid = false
          reject(`基本信息产品可售部门`)
        }
      })
    },
    // 产品可售部门change数据处理
    // handleApartmentChange (val) {
    //   if (val === '0') {
    //     const apartmentId = this.apartmentValueList.join(',')
    //     this.$set(this.form, 'apartmentId', apartmentId)
    //     this.isShowSelectApartment = false
    //   } else {
    //     this.$set(this.form, 'apartmentId', '')
    //     this.isShowSelectApartment = true
    //   }
    // },
    handleProductNameChange(val) {
      if (!this.form.couponName) {
        this.$set(this.form, 'couponName', val)
      }
    },
    setChannelID(val) {
      if (val === '0') {
        this.$set(this.form, 'channelId', '-1')
      } else {
        this.$set(this.form, 'channelId', '')
      }
    },
    handlePushRuleItem(val) {
      if (this.$product.id) {
        const DEFAULT_ITEM = JSON.parse(JSON.stringify(this.$product.DEFAULT_ITEM))
        // 基础规则
        if (val === '1' && this.form.onlineRule && this.form.onlineRule.length <= 0) {
          this.form.onlineRule = [DEFAULT_ITEM]
        } else if (val === '2' && this.form.offlineRule && this.form.offlineRule.length <= 0) {
          this.form.offlineRule = [DEFAULT_ITEM]
        }
        // 特殊规则
        if (val === '1' && this.form.onlineSpecialRule && this.form.onlineSpecialRule.length <= 0) {
          this.form.onlineSpecialRule = [{ programId: '' }]
        } else if (
          val === '2' &&
          this.form.offlineSpecialRule &&
          this.form.offlineSpecialRule.length <= 0
        ) {
          this.form.offlineSpecialRule = [{ programId: '' }]
        }
      }

      // 当取消掉 券兑付范围 为 【线上】 选项时 则 【心选膨胀】 选项也需重置勾选
      if (!val.includes('1') && val.includes('3')) {
        this.form.exchangeRange = this.form.exchangeRange
          .split(',')
          .filter((item) => {
            return item !== '3'
          })
          .join(',')
      }
    },
    handleChangeType(val) {
      this.$set(this.form, 'exchangeRange', '')
      this.$set(this.form, 'proportionData', [])
      this.$set(this.form, 'businessType', '')
      if (val === '5') {
        this.$set(this.form, 'exchangeRange', '1')
      }
      this.getBusinessTypeList()
    },
    async companyChange() {
      this.apartmentList = []
      this.apartmentList = await publicApis.apartmentList({ companyId: this.form.companyId })
      console.log(this.form.apartmentId, '=====')
      let idsList = []
      this.apartmentList.forEach((item) => {
        idsList.push(item.value)
        if (item.children) {
          item.children.forEach((i) => {
            idsList.push(i.value)
          })
        }
      })
      this.apartmentValueList = idsList
    },
    hangeDelImage() {
      this.form.cardSurfaceId = ''
    },
    handlePreview() {
      this.$refs.imagePreview.showViewer = true
    }
  }
}
</script>

<style scoped lang="scss">
.tip-card {
  color: #cbcbcb;
  font-size: 14px;
  padding: 12px 0;
}
.image-pre {
  position: relative;
  width: 380px;
  border-radius: 12px;
  .delete-img {
    display: none;
  }
  &:hover {
    .delete-img {
      border-radius: 12px;
      display: block;
      position: absolute;
      width: 380px;
      height: 200px;
      line-height: 40px;
      left: 0;
      top: 0;
      background: rgba(59, 60, 61, 0.5);
      box-sizing: content-box;
      z-index: 999;
      cursor: pointer;
      text-align: right;
      .fixed-img {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        margin: 8px 10px 0 0;
        display: block;
        font-size: 24px;
        color: white;
      }
    }
  }
}
.image-preview {
  /deep/.is-success {
    width: 280px !important;
  }
}
</style>
